var express = require('express');
var router = express.Router();
var {getUserQueryALL,getUserByPhone,addUser,delUser,updateUserAddress} = require('../db/useraction');
var {getScoreQueryALL,getScoreByPhone,addScoreTable,delScoreTable,updateScore} =require('../db/scoreaction');
var GetProb = require('../logic/IntegralLogic');

var debugMode = true;
var jsonData=JSON.stringify({phone:'18723356781',address:'重庆市',score:30000});

//响应一个json数据
var responseJSON = function(res,ret){
    if(typeof ret == 'undefined'){
        res.responseJSON({
            code:'-200',
            msg:'操作失败'
        })
    }else{
        res.responseJSON(ret);
    }
};

// ctx.response.body = `<h1>Index</h1>
// <form action="/deluserpost" method="post">
//     <p>sid: <input name="sid" value="10001"></p>
//     <p>wxid: <input name="wxid" value=""></p>
//     <p><input type="submit" value="Submit"></p>
// </form>`;

//查询所有用户数据  101
var fn_findALLUser = async (ctx, next) => {
   // ctx.response.body = `<h1>find all User</h1>`;
    getUserQueryALL(function(code){ //ctx = ??
        //发送结果
        code.code = 101;
        code = JSON.stringify(code);
        console.log(code);
    });
};
//查询指定用户数据 102
var fn_findUserByPhone = async (ctx, next) => {
   //ctx.response.body = `<h1>find user by phone</h1>`;
    ctx.req.on("data",function(data){
        console.log(data)
    })
    var json = debugMode ? JSON.parse(jsonData) : JSON.parse(ctx.request.body.json);
    phone = json.phone;
    getUserByPhone(phone,function(code){
        code.code = 102;
        code = JSON.stringify(code);
        console.log(code);
    });
};

//查询所有分数 103
var fn_findScoreAll = async(ctx,next)=>{
    getScoreQueryALL(function(code){
        code.code = 103;
        code = JSON.stringify(code);
        console.log(code);
    });
}

//查询指定分数数据 104
var fn_findScoreByPhone =async(ctx,next)=>{
    var phone = '';
    var json = debugMode ? JSON.parse(jsonData) : JSON.parse(ctx.request.body.json);
    phone = json.phone;
    getScoreByPhone(phone,function(code){
        code.code =104;
        code = JSON.stringify(code);
        console.log(code);
    })
}

//查询指定用户中奖概率 105
var fn_queryChance = async(ctx,next)=>{
    var phone = '';
    var json = debugMode ? JSON.parse(jsonData) : JSON.parse(ctx.request.body.json);
    phone = json.phone;
    getScoreByPhone(phone,function(code){
        //check result
        if(code.requestData && code.requestData.length!=0){
            var list = GetProb(code.requestData[0].score);
            code.requestData = list || [];
            code.describe = list==0 ? '积分不足' : '查询概率得到结果'+phone;
        }else{
            code.describe = '此号码没有开通';
        }
        code.code = 105;
        code = JSON.stringify(code);
        console.log(code);
    })
}
//添加新用户 106
var fn_insertUser = async(ctx,next)=>{
    var params={};
    var json = debugMode ? JSON.parse(jsonData) : JSON.parse(ctx.request.body.json);
    params.phone = json.phone;
    params.address = json.address;
    
    addUser(params,function(code){
        if(code.request=='succeed'){
            addScoreTable(params.phone,function(code){
                code.describe =params.phone+':新用户添加成功';
                code.code = 106;
                code = JSON.stringify(code);
                console.log(code);
            })
        }else{
            code.code = 106;
            code = JSON.stringify(code);
            console.log(code);
        }
    })
}

//删除指定用户(积分) 107
var fn_delUser = async(ctx,next)=>{
    var phone = '';
    var json = debugMode ? JSON.parse(jsonData) : JSON.parse(ctx.request.body.json);
    phone = json.phone;
    delScoreTable(phone,function(code){
        code.code = 107;
        if(code.request=='succeed'){
            delUser(phone,function(code){
                code.code = 107;
                code = JSON.stringify(code);
                console.log(code);
            })
        }else{
            code = JSON.stringify(code);
            console.log(code);
        }
        
    })
};

//修改指定用户地址 108
var fn_updateUser = async(ctx,next)=>{
    var params={};
    var json = debugMode ? JSON.parse(jsonData) : JSON.parse(ctx.request.body.json);
    params.phone = json.phone;
    params.address = json.address;
    
    updateUserAddress(params,function(code){
        code.code = 108;
        code = JSON.stringify(code);
        console.log(code);
    });
};

//修改指定用户积分 109
var fn_updateScore = async(ctx,next)=>{
    var params={};
    var json = debugMode ? JSON.parse(jsonData) : JSON.parse(ctx.request.body.json);
    params.phone = json.phone;
    params.score = json.score;

    updateScore(params,function(code){
        code.code = 109;
        code = JSON.stringify(code);
        console.log(code);
    })
}

var http = require('http');
//测试专用
var fn_query = async(ctx,next)=> {
    var opt ={
        hostname:'127.0.0.1',
        port:3000,
        path:'/API/102',
        method:'GET',
        headers:{
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'  
        },
        body:{phone:18723356781}
    }
    var req = http.request(opt,function(res){
        res.setEncoding('utf8');
        res.on('data',function(data){
            console.log(data);
        });
    });
    req.on('error',function(e){
        console.log(e.message);
    })
    req.end();
}


// var fn_query=async(ctx,next)=>{
//     ctx.body = JSON.stringify({phone:18723356781});
//     console.log(ctx.request.url)
// }

module.exports = {
    'GET /API/101':fn_findALLUser,      //查找所有用户
    'GET /API/102':fn_findUserByPhone,  //查找指定用户
    'GET /API/103':fn_findScoreAll,     //查找所有积分
    'GET /API/104':fn_findScoreByPhone, //查找指定积分
    'GET /API/105':fn_queryChance,      //查询概率
    'GET /API/106':fn_insertUser,       //添加用户
    'GET /API/107':fn_delUser,          //删除用户
    'GET /API/108':fn_updateUser,       //更新用户信息
    'GET /API/109':fn_updateScore,       //更新分数
    'GET /query':fn_query
};